package com.declum.archon.chunkserver.manager.disk;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class DiskManager implements IDiskManager {
	Map<String, IDiskOperator>	diskDB			= new HashMap<String, IDiskOperator>();
	private FreeDiskSorting		freeDiskSorting	= new FreeDiskSorting();

	@Override
	public void addDisk(String path) throws IOException {
		IDiskOperator diskInfo = DiskInfo.getInstance(path);
		this.diskDB.put(diskInfo.getPath(), diskInfo);
	}

	@Override
	public void balanceDataBetweenDisks() {

	}

	@Override
	public IDiskOperator[] getDiskInfo() {
		return this.diskDB.values().toArray(new DiskInfo[] {});
	}

	@Override
	public String[] getDiskPath() {
		return this.diskDB.keySet().toArray(new String[] {});
	}

	@Override
	public synchronized IDiskOperator getFreeDisk() {
		synchronized (this.freeDiskSorting) {
			IDiskOperator[] diskInfo = this.getDiskInfo();
			if ((diskInfo != null) && (diskInfo.length > 0)) {
				this.freeDiskSorting = new FreeDiskSorting();
				Arrays.sort(diskInfo, this.freeDiskSorting);
				return diskInfo[0];
			}
			return null;
		}
	}

	@Override
	public IDiskOperator releaseDisk(String path) {
		File file = new File(path);
		String absolutePath = file.getAbsolutePath();
		IDiskOperator info = this.diskDB.remove(absolutePath);
		info.release();
		return info;
	}
}
